package se.miun.datatek;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;

import android.content.Context;
import android.database.Cursor;




public class CSVWriter 
{

	public CSVWriter()
	{}
	
	
	public void writeSchemaToCSV()
	{
		
		Calendar cal = Calendar.getInstance();
		
		try
		{
			Cursor cursor = DAO.dbHelper.getReadableDatabase().rawQuery("SELECT * FROM schema2",null);
			cursor.moveToFirst();

			BufferedWriter print = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/sdcard/Infantum/schema/vecka_"+cal.get(Calendar.WEEK_OF_YEAR)+".csv"), "ISO-8859-1"));
			
			
			//Write the columns to the CSV file
			for(int numOfCol =0; numOfCol < 11; numOfCol++)
			{
				if(numOfCol != 10)
				{
					print.write(cursor.getColumnName(numOfCol)+";");
					System.out.print(cursor.getColumnName(numOfCol)+";");
				}	
				else
				{	print.write(cursor.getColumnName(numOfCol));
					print.write("\r\n");
					System.out.println(cursor.getColumnName(numOfCol));
					System.out.println();
				}
			}
			
			
			//Write data that belongs to the columns
			do
			{
				print.write( cursor.getInt(0)+";"+cursor.getInt(1)+";"+cursor.getInt(2)+";"+cursor.getInt(3)
						+";"+cursor.getInt(4)+";"+cursor.getInt(5)+";"+cursor.getInt(6)+";"+cursor.getInt(7)+
						";"+cursor.getInt(8)+";"+cursor.getInt(9)+";"+cursor.getInt(10));
				System.out.print(cursor.getInt(0)+";"+cursor.getInt(1)+";"+cursor.getInt(2)+";"+cursor.getInt(3)
						+";"+cursor.getInt(4)+";"+cursor.getInt(5)+";"+cursor.getInt(6)+";"+cursor.getInt(7)+
						";"+cursor.getInt(8)+";"+cursor.getInt(9)+";"+cursor.getInt(10));
				System.out.println();
				print.write("\r\n");
				
			}
			while(cursor.moveToNext() != false);
			
			print.close();
			
		}
		catch (FileNotFoundException e) 
		{
			System.err.println("COULD NOT FIND FILE");
			e.printStackTrace();
		} 
		catch (UnsupportedEncodingException e)
		{
			System.err.println("ENCODING NOT SUPPORTED");
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			System.err.println("COULD NOT WRITE TO FILE");
			e.printStackTrace();
		}
		
	}
	
	
	
	
	
	
	
	
	
}


